import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as SellChanceMainAction from '../../actions/sellChanceMain'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import WeaFormmodeTop from '../WeaFormmodeTop'
import WeaCrmTableEdit from '../WeaCrmTableEdit'
import CustomerContact from '../CustomerContact.js'
import RemindSetModal from '../contact/remindSetModal'
import CrmTools from '../crmTools';

import { WeaErrorPage,WeaTools,WeaSearchGroup, WeaRightMenu,WeaAlertPage} from 'ecCom'


import {Button,Form,Modal,message,Spin} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class EditSellChance extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            datas:[]
        }
    }
    componentDidMount() {
        const {actions,location:{query}} = this.props;
        actions.sellChanceForm({operation:"edit",sellChanceId:query.sellChanceId});
    }
    componentWillReceiveProps(nextProps) {

    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.mainTableInfo,nextProps.mainTableInfo)||
        !is(this.props.subTableInfo,nextProps.subTableInfo)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.subTableColumn,nextProps.subTableColumn)||
        !is(this.props.sellChanceId,nextProps.sellChanceId)||
        !is(this.props.editSelectKey,nextProps.editSelectKey)||
        !is(this.props.customerId,nextProps.customerId)||
        !is(this.props.remindInfo,nextProps.remindInfo)||
        !is(this.props.hasright,nextProps.hasright);
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,actions,title,mainTableInfo,subTableInfo,subTableColumn,editSellChanceTab,editSelectKey,sellChanceId,customerId,remindInfo,hasright} = this.props;
        const columns = subTableInfo.get('columnDefine');
        const dataSource = subTableInfo.get('columnData');
        if(hasright == "-1"){
            return (
				<div className="align-center top40">
					<Spin size="large"></Spin>
				</div>);
        }else if(!hasright){
            return (
                <WeaAlertPage>
                    <div className="color-black">
                        对不起，您暂时没有权限
                    </div>
                </WeaAlertPage>);
        }else{
            return (
                <div>
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                        <WeaFormmodeTop 
                            title={"商机"}
                            loading={loading}
                            icon={<i className='icon-coms-crm' />}
                            iconBgcolor='#96358a'
                            buttons={this.getButtons()}
                            buttonSpace={10}
                            showDropIcon={true}
                            dropMenuDatas={this.getRightMenu()}
                            onDropMenuClick={this.onRightMenuClick.bind(this)}
                            tabDatas={editSellChanceTab.toJS()}
                            selectedKey={editSelectKey}
                            onChange={this.sellChanceChangeData.bind(this)}
                        >
                        {
                            editSelectKey =="sellchance" &&
                            <div>
                                <Form horizontal>{this.getBasicInfo()}</Form>
                                <WeaCrmTableEdit 
                                    title={"产品"} 
                                    showGroup={true} 
                                    needAdd={true} 
                                    needCopy={false}
                                    columns={subTableColumn.toJS()} 
                                    datas={dataSource.toJS()}
                                    onChange={this.editTableDatas.bind(this)}
                                />
                            </div>
                        }
                        {
                            editSelectKey =="exchange" &&
                            <div className="contact-logs-container">
                                <CustomerContact ref="contactlogs" type={"sellchance"} params={{from:"all",customerId:customerId,sellChanceId:sellChanceId}} />
                                <RemindSetModal ref="remindSetInSellchance" remindInfo={remindInfo} customerId={customerId} saveRemindSetting={this.saveRemindSetting}/>
                            </div>
                        }
                        </WeaFormmodeTop>
                </WeaRightMenu>
                </div>
            )
        }
    }
     onRightMenuClick(key){
    	 const {actions,} = this.props;
    	if(key == '0'){
            this.saveProducts();
    	}
    	if(key == '1'){
    		// actions.batchSubmitClick({checkedKeys:`${selectedRowKeys.toJS()}`})
    	}
    }
    getRightMenu(){
    	const {editSelectKey} = this.props;
        let btns = [];
        if(editSelectKey=="sellchance"){
            btns.push({
                icon: <i className='icon-Right-menu-search'/>,
                content:'保存',
                key:0
            });
        }
        btns.push({
            icon: <i className='icon-Right-menu-batch'/>,
            content:'收藏',
        });
    	btns.push({
            icon: <i className='icon-Right-menu-batch'/>,
            content:'帮助',
        });
    	return btns
    }
     getButtons() {
        const {editSelectKey} = this.props;
        let btnArr = [];
       { editSelectKey=="sellchance" && btnArr.push(<Button type="primary" onClick={this.saveProducts}>保存</Button>)}
       { editSelectKey=="exchange" && btnArr.push(<Button type="primary" onClick={this.setRemind.bind(this)}>联系提醒设置</Button>)}
        return btnArr
    }
    getBasicInfo=()=> {
       const { mainTableInfo,actions } = this.props;
		let group = [];
		mainTableInfo.toJS().map(c =>{
			let items = [];
			c.items.map(field => {
                    items.push({
                        com:(<FormItem
                            label={`${field.label}`}
                            labelCol={{span: `${field.labelcol}`}}
                            wrapperCol={{span: `${field.fieldcol}`}}>
                                { CrmTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field,this.callback)}
                            </FormItem>),
                        colSpan:1
                    })
			});
			group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
		}); 
		return group
    }
    callback=(field,value,id,name)=>{
        const {sellChanceId,actions } = this.props;
        let fit = field.formItemType.toUpperCase();
        const fieldName=field.domkey[0];
        if(( fit === "INPUT" ||fit === "TEXTAREA") && value !== field.value){
             if( field.viewAttr== 3 && value == ""){
                 return false;
             }else{
                 const params ={
                    sellChanceId:sellChanceId,
                     fieldName:fieldName, 
                     oldValue:field.value,   
                     newValue:value, 
                 };
                 actions.sellChanceEdit(params);
             }  
        }
        if(fit === "SELECT" || fit === "CHECKBOX" || fit === "BROWSER" || fit === "DATEPICKER"){
              const params ={
                 sellChanceId:sellChanceId,
                 fieldName:fieldName , 
                 oldValue:field.value,   
                 newValue:value, 
             };
                 actions.sellChanceEdit(params);
        }
     }
    editTableDatas(datas){
      //  console.log("明细表",datas);
        this.setState({datas})

    }
    saveProducts=(datas)=>{
        const {actions,subTableInfo,sellChanceId} = this.props;
        const dataSource = subTableInfo.get('columnData');
        let dataValue = [];
        if(!this.state.datas.length){ dataValue = dataSource.toJS(); }else{dataValue = this.state.datas}
        //console.log(dataValue)
        actions.saveProduct({sellChanceId:sellChanceId,productList:JSON.stringify(dataValue)});
    }
    sellChanceChangeData(key){
        const {actions} = this.props;
        actions.editSellChanceChangeTab(key);
    }
    setRemind(){
        const {actions,customerId} = this.props;
        actions.getRemindInfo(customerId);
        console.log(this.refs.remindSetInSellchance)
     //  this.refs.remindSetInSellchance.setContactVisible(true);
    }
    saveRemindSetting=(params)=>{
        const {actions} = this.props;
        actions.saveRemindSet(params);
    }
   
}


class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

EditSellChance = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(EditSellChance);

EditSellChance = createForm({
	// onFieldsChange(props, fields) {
    //     props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    // },
	// mapPropsToFields(props) {
	// 	return props.orderFields.toJS();
  	// }
})(EditSellChance);

function mapStateToProps(state) {
    // return {...state.crmContactQuery}
	const {crmsellChanceMain} = state;
    return {
    	loading: crmsellChanceMain.get('loading'),
        title: crmsellChanceMain.get('title'),
        mainTableInfo: crmsellChanceMain.get('mainTableInfo'),
        subTableInfo: crmsellChanceMain.get('subTableInfo'),
        subTableColumn:crmsellChanceMain.get('subTableColumn'),
        sellChanceId:crmsellChanceMain.get('sellChanceId'),
        editSellChanceTab:crmsellChanceMain.get('editSellChanceTab'),
        editSelectKey:crmsellChanceMain.get('editSelectKey'),
        customerId:crmsellChanceMain.get('customerId'),
        remindInfo:crmsellChanceMain.get('remindInfo'),
        hasright:crmsellChanceMain.get('hasright')
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...SellChanceMainAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(EditSellChance);
